define(['jquery', 'bootstrap', 'backend', 'table', 'form'], function ($, undefined, Backend, Table, Form) {

    var Controller = {
        index: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'order/order_master/index' + location.search,
                    add_url: 'order/order_master/add',
                    edit_url: 'order/order_master/edit',
                    del_url: 'order/order_master/del',
                    multi_url: 'order/order_master/multi',
                    import_url: 'order/order_master/import',
                    table: 'order_master',
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                fixedColumns: true,
                fixedRightNumber: 1,
                columns: [
                    [
                        { field: 'id', title: __('Id'), operate: false },
                        // {field: 'order_master_id', title: __('Order_master_id')},
                        {
                            field: 'order_goods_id', operate: false, title: '检测项目', formatter: function (value, row, index) {
                                return row.ordergoods?.map(item => {
                                    return `<div style="text-align:left;">${item.title}${item.status == -10 ? '<span style="color:red;">(退)</span>' : ''}</div>`
                                }).join('') || '-'
                            }
                        },
                        {
                            field: 'user.nickname', title: '开单医生', formatter: function (value, row, index) {
                                return `<div>姓名:${row.user?.nickname}</div><div>手机号:${row.user?.mobile}</div>`
                            }
                        },
                        {
                            field: 'sole_id', title: '销售', operate: false, formatter: function (value, row, index) {
                                return `<div>姓名:${row.sale?.nickname}</div><div>手机号:${row.sale?.mobile}</div>`
                            }
                        },
                        {
                            field: 'order_tube', title: '试管', formatter: function (value, row, index) {
                                let html = '';
                                row.order_tube.forEach(item => {
                                    html += `<div>${item.biaoben_rongqi_name}：${item.tube_number}</p>
                            </div>`
                                })
                                return html

                            }
                        },
                        {
                            field: 'order.hospital_id', title: '医院', formatter: function (value, row, index) {
                                return row.hospital_name
                            }, searchList: $.getJSON('hospital/hospital/getJson')
                        },
                        // {field: 'goods_package_id', title: __('Goods_package_id')},
                        {
                            field: 'order.username', title: __('Username'), operate: 'LIKE', table: table, class: 'autocontent', formatter: function (value, row, index) {
                                return row.username
                            }
                        },
                        { field: 'userphone', title: __('Userphone'), operate: 'LIKE', table: table, class: 'autocontent', formatter: Table.api.formatter.content },
                        { field: 'age', title: __('Age'), operate: false },
                        { field: 'gender', title: __('Gender'), operate: false },
                        { field: 'pay_type', title: __('Pay_type'), searchList: { "10": __('Pay_type 10'), "20": __('Pay_type 20'),"30": __('Pay_type 30') }, formatter: Table.api.formatter.normal },
                        { field: 'out_trade_no', title: __('Out_trade_no'), operate: 'LIKE', table: table, class: 'autocontent', formatter: Table.api.formatter.content },
                        // {field: 'transaction_id', title: __('Transaction_id'), operate: 'LIKE', table: table, class: 'autocontent', formatter: Table.api.formatter.content},
                        // {field: 'out_refund_no', title: __('Out_refund_no'), operate: 'LIKE', table: table, class: 'autocontent', formatter: Table.api.formatter.content},
                        // {field: 'refund_id', title: __('Refund_id'), operate: 'LIKE', table: table, class: 'autocontent', formatter: Table.api.formatter.content},
                        { field: 'order_sn', title: __('Order_sn'), operate: false, table: table, class: 'autocontent', formatter: Table.api.formatter.content },
                        { field: 'price', title: __('Price'), operate: false },
                        { field: 'original_price', title: __('Original_price'), operate: false },
                        // {field: 'pay_status', title: __('Pay_status'), searchList: {"0":__('Pay_status 0'),"1":__('Pay_status 1')}, formatter: Table.api.formatter.status},
                        { field: 'pay_time', title: __('Pay_time'), operate: 'RANGE', addclass: 'datetimerange', autocomplete: false, formatter: Table.api.formatter.datetime },
                        {
                            field: 'order.status', title: __('Status'), searchList: { "0": __('Status 0'), "10": __('Status 10'), "20": __('Status 20'), "30": __('Status 30'), "-10": __('Status -10'), "-20": __('Status -20') }, formatter: function (value, row, index) {
                                return Table.api.formatter.status.call(this, row.status, row, index)
                            }
                        },
                        // {field: 'report_status', title: __('Report_status'), searchList: {"0":__('Report_status 0'),"10":__('Report_status 10'),"20":__('Report_status 20'),"30":__('Report_status 30')}, formatter: Table.api.formatter.status},
                        // {field: 'report_image', title: __('Report_image'), operate: false, events: Table.api.events.image, formatter: Table.api.formatter.image},
                        { field: 'quyangtime', title: __('Quyangtime'), operate: 'RANGE', addclass: 'datetimerange', autocomplete: false, formatter: Table.api.formatter.datetime },
                        { field: 'songjiantime', title: __('Songjiantime'), operate: 'RANGE', addclass: 'datetimerange', autocomplete: false, formatter: Table.api.formatter.datetime },
                        { field: 'overtime', title: __('Overtime'), operate: 'RANGE', addclass: 'datetimerange', autocomplete: false, formatter: Table.api.formatter.datetime },
                        { field: 'quxiaotime', title: __('Quxiaotime'), operate: 'RANGE', addclass: 'datetimerange', autocomplete: false, formatter: Table.api.formatter.datetime },
                        { field: 'tuikuantime', title: __('Tuikuantime'), operate: 'RANGE', addclass: 'datetimerange', autocomplete: false, formatter: Table.api.formatter.datetime },
                        {
                            field: 'order.createtime', title: __('Createtime'), operate: 'RANGE', addclass: 'datetimerange', autocomplete: false, formatter: function (value, row, index) {
                                return Table.api.formatter.datetime(row.createtime, row, index);
                            }
                        },
                        {field: 'buttons', title: '操作', table: table, events: Table.api.events.operate, buttons:[
                            {
                                name: 'refund',
                                text: __('退款'),
                                classname: 'btn btn-xs btn-primary btn-dialog',
                                url: 'order/order_master/refund',
                                callbacks: function (data,row,index) {
                                    // console.log(row.report_image);
                                    // Table.api.formatter.images.call(this,row.report)
                                },
                                visible: function (row) {
                                    //返回true时按钮显示,返回false隐藏
                                    return  row.status > 0 && row.status < 30;
                                }
                            }
                        ],formatter: Table.api.formatter.buttons}
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        add: function () {
            var _debounce = debounce(function (ids) {
                let doctor_id = $("#c-user_id").val()
                if (!doctor_id || !ids) {
                    $("#total").text( 0)
                    $("#rongqiview").html('')
                    return
                }
                
                $.ajax({
                    url: 'order/order_master/getGoodsInfo',
                    type: 'POST',
                    data: { ids: ids ,doctor_id},
                    success: function (res) {
                        let rongqiList = res.rongqiList || []
                        let html = ``;
                        rongqiList.forEach(function (item, index) {
                            html += `<div class="form-group">
                    <label class="control-label col-xs-12 col-sm-2">${item.title}:</label>
                    <div class="col-xs-12 col-sm-8">
                    <input style="width: 200px;" class="form-control" data-rule="required" name="row[rongqi][id][]" type="hidden" value="${item.id}">
                    <input style="width: 200px;" class="form-control" data-rule="required" name="row[rongqi][tube_number][]" type="text" >
                    </div>
                </div>`
                        })
                        $("#rongqiview").html(html)
                        $("#total").text(res.total || 0)
                    }
                })
            }, 500)
            $(document).on("change", "#c-order_goods_id", function () {
                var order_goods_id = $(this).val();
                _debounce(order_goods_id)

            })
            Controller.api.bindevent();
        },
        edit: function () {
            Controller.api.bindevent();
        },
        refund: function () {
            Controller.api.bindevent();
        },
        api: {
            bindevent: function () {
                Form.api.bindevent($("form[role=form]"));
            }
        }
    };

    function debounce(func, delay) {
        let timer = null; // 用于存储定时器ID

        // 返回一个新函数，作为事件触发时的执行函数
        return function (...args) {
            // 每次触发事件时，清除之前的定时器
            if (timer) {
                clearTimeout(timer);
            }

            // 重新设置定时器，延迟执行目标函数
            timer = setTimeout(() => {
                // 执行目标函数，并绑定正确的this和参数
                func.apply(this, args);
                timer = null; // 执行后清空定时器
            }, delay);
        };
    }
    return Controller;
});
